package org.jeecg.modules.materia.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.http.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.content.controller.ContentTemplateController;
import org.jeecg.modules.content.entity.ContentGoto;
import org.jeecg.modules.content.entity.ContentInfo;
import org.jeecg.modules.content.service.IContentInfoService;
import org.jeecg.modules.materia.entity.CrdMaterialInfo;
import org.jeecg.modules.materia.entity.GroupInfoBo;
import org.jeecg.modules.materia.service.ICrdMaterialInfoService;
import org.jeecg.modules.oss.service.IOSSFileService;
import org.jeecg.util.DeleteFlagEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 素材信息
 * @Author: jeecg-boot
 * @Date: 2020-05-02
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "素材信息")
@RestController
@RequestMapping("/materia/crdMaterialInfo")
public class CrdMaterialInfoController extends JeecgController<CrdMaterialInfo, ICrdMaterialInfoService> {
    @Autowired
    private ICrdMaterialInfoService crdMaterialInfoService;

    @Autowired
    private IContentInfoService contentInfoService;

    /**
     * 分页列表查询
     *
     * @param crdMaterialInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "素材信息-分页列表查询")
    @ApiOperation(value = "素材信息-分页列表查询", notes = "素材信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CrdMaterialInfo crdMaterialInfo,
                                   Integer materType,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
//        crdMaterialInfo.setDelFlag(0);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String keyword = req.getParameter("keyword");
        String materialName = req.getParameter("materialName");
        String groupId = req.getParameter("groupId");
        Integer materialType = crdMaterialInfo.getMaterialType();

//        QueryWrapper<CrdMaterialInfo> queryWrapper = QueryGenerator.initQueryWrapper(crdMaterialInfo, req.getParameterMap());
        QueryWrapper<CrdMaterialInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0);
        queryWrapper.orderByDesc("create_time");
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like("keyword",keyword+",");
        }
        if(StringUtils.isNotBlank(materialName)){
            queryWrapper.like("material_name",materialName);
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        if(StringUtils.isNotBlank(groupId)){
            queryWrapper.eq("group_id",groupId);
        }
        if(null != materType && materType == 1){
            queryWrapper.eq("create_by",sysUser.getUsername());
        }
        if(null != materType && materType == 3){
            queryWrapper.like("departs",loginUser.getDepartIds());
        }
        if(materialType != null){
            queryWrapper.eq("material_type",materialType);
        }
        Page<CrdMaterialInfo> page = new Page<CrdMaterialInfo>(pageNo, pageSize);
        IPage<CrdMaterialInfo> pageList = crdMaterialInfoService.page(page, queryWrapper);
        List<CrdMaterialInfo> list = pageList.getRecords();
        List<CrdMaterialInfo> newList = new ArrayList<>();
        for(CrdMaterialInfo info : list){
            if(null != info && !StringUtil.isEmpty(info.getKeyword()) && info.getKeyword().endsWith(",")){
                info.setKeyword(info.getKeyword().substring(0,info.getKeyword().length()-1));
            }else{
                info.setKeyword("");
            }
            //查询是否有压缩
//            String compress = ossFileService.getCompress(info.getMaterialUrl());
//            if(org.springframework.util.StringUtils.isEmpty(compress)){
//                info.setMaterialUrl(compress);
//            }

            newList.add(info);
        }
        pageList.setRecords(newList);
        return Result.ok(pageList);
    }

    @Autowired
    IOSSFileService ossFileService;

    /**
     * 添加
     *
     * @param crdMaterialInfo
     * @return
     */
    @AutoLog(value = "素材信息-添加")
    @ApiOperation(value = "素材信息-添加", notes = "素材信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CrdMaterialInfo crdMaterialInfo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        crdMaterialInfo.setCreateBy(sysUser.getUsername());
        crdMaterialInfo.setCreateTime(new Date());
        crdMaterialInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
        if(StringUtils.isBlank(crdMaterialInfo.getGroupId())){
            crdMaterialInfo.setGroupId("0");
        }
        String keyword = crdMaterialInfo.getKeyword();
        keyword = StringUtils.replace(keyword,"，",",");
        if(!StringUtils.endsWith(keyword,",")){
            keyword = keyword + ",";
        }

        String[] departs = crdMaterialInfo.getDepart();
        String depart = "";
        if(departs != null){
            for(int i = 0 ; i < departs.length ; i++){
                depart += departs[i]+",";
            }
            crdMaterialInfo.setDeparts(depart);
        }

        crdMaterialInfo.setKeyword(keyword);
        crdMaterialInfoService.save(crdMaterialInfo);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param crdMaterialInfo
     * @return
     */
    @AutoLog(value = "素材信息-编辑")
    @ApiOperation(value = "素材信息-编辑", notes = "素材信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CrdMaterialInfo crdMaterialInfo) {
        crdMaterialInfoService.updateById(crdMaterialInfo);
        return Result.ok("编辑成功!");
    }

    /**
     * 编辑名称
     *
     * @param crdMaterialInfo
     * @return
     */
    @AutoLog(value = "素材信息-编辑名称")
    @ApiOperation(value = "素材信息-编辑名称", notes = "素材信息-编辑名称")
    @PostMapping(value = "/editName")
    public Result<?> editName(@RequestBody CrdMaterialInfo crdMaterialInfo) {
        CrdMaterialInfo dbCrdMaterialInfo = crdMaterialInfoService.getById(crdMaterialInfo.getId());
        dbCrdMaterialInfo.setMaterialName(crdMaterialInfo.getMaterialName());
        if(!StringUtils.isEmpty(crdMaterialInfo.getGroupId())){
            dbCrdMaterialInfo.setGroupId(crdMaterialInfo.getGroupId());
            dbCrdMaterialInfo.setGroupName(crdMaterialInfo.getGroupName());
        }
        crdMaterialInfoService.updateById(dbCrdMaterialInfo);
        return Result.ok("成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "素材信息-通过id删除")
    @ApiOperation(value = "素材信息-通过id删除", notes = "素材信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        CrdMaterialInfo crdMaterialInfo = crdMaterialInfoService.getById(id);
        //检查是否使用
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.or().like("content_title",crdMaterialInfo.getMaterialUrl());
        queryWrapper.or().like("content_sub_title",crdMaterialInfo.getMaterialUrl());
        queryWrapper.or().like("content_introduce",crdMaterialInfo.getMaterialUrl());
        queryWrapper.or().like("mb_logo_url",crdMaterialInfo.getMaterialUrl());
        queryWrapper.or().like("content",crdMaterialInfo.getMaterialUrl());
        List<ContentInfo> contentInfoList  = contentInfoService.list(queryWrapper);
        if(null == contentInfoList || contentInfoList.size() == 0){
            crdMaterialInfo.setDelFlag(1);
            crdMaterialInfoService.updateById(crdMaterialInfo);
//            if(StringUtils.isNotBlank(crdMaterialInfo.getMaterialUrl())){
//                OssBootUtil.deleteUrl(crdMaterialInfo.getMaterialUrl());
//            }
//
//            if(StringUtils.isNotBlank(crdMaterialInfo.getMaterialCoverUrl())){
//                OssBootUtil.deleteUrl(crdMaterialInfo.getMaterialCoverUrl());
//            }

            //crdMaterialInfoService.removeById(id);
            return Result.ok("删除成功!");
        }else{
            //组装错误信息
            String msg = "删除失败，该素材已经被以下文章使用";
            for(ContentInfo contentInfo : contentInfoList){
                msg += contentInfo.getContentTitle() +",";
            }
            return  Result.error(msg.substring(0,msg.length()-1));
        }

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "素材信息-批量删除")
    @ApiOperation(value = "素材信息-批量删除", notes = "素材信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.crdMaterialInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "素材信息-通过id查询")
    @ApiOperation(value = "素材信息-通过id查询", notes = "素材信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CrdMaterialInfo crdMaterialInfo = crdMaterialInfoService.getById(id);
        return Result.ok(crdMaterialInfo);
    }


    /**
     * 获取keywords
     *
     * @return
     */
    @AutoLog(value = "素材信息-获取关键字集合")
    @ApiOperation(value = "素材信息-获取关键字集合", notes = "素材信息-获取关键字集合")
    @GetMapping(value = "/getKeywords")
    public Result<?> getKeywords() {
        QueryWrapper<CrdMaterialInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("keyword");
        List<CrdMaterialInfo> crdMaterialInfos = crdMaterialInfoService.list(queryWrapper);
        List<String> keywords = new ArrayList<>();
        crdMaterialInfos.forEach(crdMaterialInfo->{
            if(StringUtils.isNotBlank(crdMaterialInfo.getKeyword())){
                String keyword = crdMaterialInfo.getKeyword();
                keyword = StringUtils.removeEnd(keyword,",");
                String[] arr = keyword.split(",");
                keywords.addAll(Arrays.asList(arr));
            }
        });
        return Result.ok(keywords);
    }




    /**
     * 导出excel
     *
     * @param request
     * @param crdMaterialInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CrdMaterialInfo crdMaterialInfo) {
        return super.exportXls(request, crdMaterialInfo, CrdMaterialInfo.class, "素材信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CrdMaterialInfo.class);
    }

    /**
     * 获取分组信息
     *
     * @return
     */
    @GetMapping(value = "/queryGroupInfo")
    public Result<?> queryGroupInfo(Integer materialType) {
        List<GroupInfoBo>  list = crdMaterialInfoService.queryGroupInfo(materialType);
        return Result.ok(list);
    }


}
